package com.leetcode.multithreading.anyan;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class Jm_User {
    private static AtomicReferenceFieldUpdater<Jm_User, String> nameUpdater = AtomicReferenceFieldUpdater.newUpdater(Jm_User.class, String.class, "name");
    private static AtomicIntegerFieldUpdater<Jm_User> ageUpdater = AtomicIntegerFieldUpdater.newUpdater(Jm_User.class, "age");
    private volatile String name;
    private volatile int age;

    public Jm_User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void lazySetName(String name) {
        nameUpdater.lazySet(this, name);
    }

    public String getSetName(String name) {
        return nameUpdater.getAndSet(this, name);
    }

    public void compareAndSetName(String exceptedName, String newName) {
        nameUpdater.compareAndSet(this, exceptedName, newName);
    }

    public void lazySetAge(int age) {
        ageUpdater.lazySet(this, age);
    }

    public Integer getSetAge(int age) {
        return ageUpdater.getAndSet(this, age);
    }

    public void compareAndSetAge(int exceptedAge, int newAge) {
        ageUpdater.compareAndSet(this, exceptedAge, newAge);
    }

    public static class AtomicTest {
        public void run() {
            Jm_User user = new Jm_User("Atomic", 10);
            user.compareAndSetName("Atomic", "Ass");
            user.compareAndSetAge(10, 11);
            System.out.println(user.getName() + user.getAge());
        }

        public static void main(String[] args) throws Exception {
            new AtomicTest().run();
        }
    }
}
